package com.bmob.lover.ui.fragment.lover

import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton
import com.qmuiteam.qmui.qqface.QMUIQQFaceView
import com.qmuiteam.qmui.util.QMUIColorHelper
import com.qmuiteam.qmui.util.QMUIResHelper
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.theone.common.ext.dp2px
import com.theone.common.ext.invisible
import com.theone.common.ext.matchParent
import com.theone.common.ext.visible
import com.bmob.lover.R
import com.bmob.lover.app.widget.OffsetLinearLayoutManager
import com.bmob.lover.data.model.enums.BackgroundType
import com.bmob.lover.data.constant.DEFAULT_DYNAMIC_BG
import com.bmob.lover.data.model.bean.Lover
import com.bmob.lover.ui.adapter.LoverAdapter
import com.bmob.lover.ui.fragment.base.BasePagerFragment
import com.bmob.lover.ui.fragment.user.UserBgFragment
import com.bmob.lover.viewmodel.LoverViewModel
import com.theone.mvvm.core.app.util.glide.GlideUtil
import com.theone.mvvm.ext.qmui.updateStatusBarMode

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-04-22 14:00
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
class LoverFragment :
    BasePagerFragment<Lover, LoverViewModel>() {


    private lateinit var mCover: ImageView
    private var mIsVisible = false
    private var mTitleView: QMUIQQFaceView? = null
    private var mSearchBtn: QMUIAlphaImageButton? = null
    private var mMaxOffsetHeight: Float = 0f
    private var isLightMode: Boolean = true
    private var mStatusBarHeight = 0

    override fun showTopBar(): Boolean = true

    override fun translucentFull(): Boolean = true

    override fun createAdapter(): BaseQuickAdapter<Lover, *> = LoverAdapter()

    override fun isNeedChangeStatusBarMode(): Boolean = true

    override fun isStatusBarLightMode(): Boolean = isLightMode

    override fun isLazyLoadData(): Boolean = false

    override fun initView(root: View) {
        super.initView(root)
        mStatusBarHeight = QMUIStatusBarHelper.getStatusbarHeight(context) / 2
        getTopBar()?.run {
            mTitleView = setTitle(R.string.app_name).apply {
                setTextColor(getColorAlpha(
                    0.0f,
                    R.color.qmui_config_color_gray_1
                ))
            }
            mSearchBtn = addRightImageButton(R.drawable.icon_add_light, R.id.topbar_search).apply {
                setOnClickListener {
                    startFragment(LoverPublishFragment())
                }
            }
            setBackgroundAlpha(0)
        }
    }

    override fun initAdapter() {
        super.initAdapter()
        val mBannerHeight = dp2px(250)
        mMaxOffsetHeight = (mBannerHeight - QMUIResHelper.getAttrDimen(
            mActivity,
            R.attr.qmui_topbar_height
        )).toFloat()
        mCover = ImageView(context).apply {
            layoutParams = ViewGroup.LayoutParams(matchParent, mBannerHeight)
            scaleType = ImageView.ScaleType.CENTER_CROP
            setOnClickListener {
                startFragment(UserBgFragment.newInstance(BackgroundType.DYNAMIC))
            }
            invisible()
        }
        getAdapter().addHeaderView(mCover)
    }

    override fun initData() {
        mAppVm.getUserInfoLiveData().value?.let {
            GlideUtil.load(context, if(it.ringBg.isNullOrEmpty()) DEFAULT_DYNAMIC_BG else it.ringBg, mCover)
        }
    }

    override fun createObserver() {
        super.createObserver()
        mAppVm.getUserInfoLiveData().observe(this, androidx.lifecycle.Observer {
            GlideUtil.load(context, it.ringBg, mCover)
        })
    }

    override fun onFirstLoadSuccess(data: List<Lover>) {
        mCover.visible()
        super.onFirstLoadSuccess(data)
        setStatusBarMode(false)
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

    }

    override fun initRecyclerView() {
        super.initRecyclerView()
        getRecyclerView().setItemViewCacheSize(30)
        getRecyclerView().addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if(getAdapter().data.size  == 0) return
                val layoutManager = recyclerView.layoutManager as OffsetLinearLayoutManager
                val y = layoutManager.computeVerticalScrollOffset(null)
                val percent: Float = if (y > mMaxOffsetHeight)
                    1.0f
                else
                    y / mMaxOffsetHeight
                val isLight = percent > 0.5
                if (!isLightMode && isLight) {
                    setStatusBarMode(true)
                } else if (isLightMode && !isLight) {
                    setStatusBarMode(false)
                }
                // 更改Title的字体颜色
                mTitleView?.setTextColor(
                    getColorAlpha(
                        percent,
                        R.color.qmui_config_color_gray_1
                    )
                )
                //显示的时候才做更改
                mSearchBtn?.setImageResource(if (isLight) R.drawable.icon_add_dark else R.drawable.icon_add_light)

                getTopBar()?.run {
                    // 更改底部分割线的颜色
                    updateBottomSeparatorColor(
                        getColorAlpha(
                            percent,
                            R.color.qmui_config_color_separator
                        )
                    )
                    // 更改背景颜色
                    setBackgroundColor(
                        getColorAlpha(
                            percent,
                            R.color.qmui_config_color_white
                        )
                    )
                }
                //大于0说明有播放

                //大于0说明有播放
                if (GSYVideoManager.instance().playPosition >= 0) {
                    //当前播放的位置
                    val position = GSYVideoManager.instance().playPosition
                    //对应的播放列表TAG
                    if (GSYVideoManager.instance()
                            .playTag == LoverAdapter.TAG && (position < layoutManager.findFirstVisibleItemPosition() || position > layoutManager.findLastVisibleItemPosition())
                    ) {
                        releaseAllVideos()
                        getAdapter().notifyItemChanged(position)
                    }
                }
            }
        })
    }

    /**
     * 更改状态栏模式
     * @param isLight
     */
    private fun setStatusBarMode(isLight: Boolean) {
        isLightMode = isLight
        if (mIsVisible)
            updateStatusBarMode(isLight)
    }

    /**
     * @TODO 根据百分比获取一个颜色的alpha值
     * @param percent 百分比
     * @param color   颜色
     */
    private fun getColorAlpha(percent: Float, color: Int): Int {
        return QMUIColorHelper.setColorAlpha(
            ContextCompat.getColor(mActivity, color),
            percent
        )
    }

    /**
     * 重写父类方法更换LayoutManager
     */
    override fun getLayoutManager(): RecyclerView.LayoutManager {
        return OffsetLinearLayoutManager(mActivity)
    }

    override fun onMoveTarget(offset: Int) {
        if (offset > mStatusBarHeight && !isLightMode) {
            setStatusBarMode(true)
        } else if (offset < mStatusBarHeight && isLightMode) {
            setStatusBarMode(false)
        }
    }

    override fun onLazyResume() {
        mIsVisible = true
        GSYVideoManager.onResume()
        super.onLazyResume()
    }

    override fun onPause() {
        super.onPause()
        mIsVisible = false
        GSYVideoManager.onPause()
    }
    private fun releaseAllVideos() {
        //如果滑出去了上面和下面就是否，和今日头条一样
        GSYVideoManager.releaseAllVideos()
    }


    fun isFull(): Boolean {
        return (getAdapter() as LoverAdapter).isFull()
    }

    @Override
    override fun onDestroy() {
        (getAdapter() as LoverAdapter).onDestroy()
        releaseAllVideos()
        super.onDestroy()
    }

    public override fun onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(mActivity)) {
            return
        }
        super.onBackPressed()
    }

}